JavaScript Pocket Reference by David Flanagan

JavaScript Pocket Reference by David Flanagan

Author:David Flanagan [David Flanagan]
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Programming Languages / JavaScript
ISBN: 9781449316617
Publisher: O'Reilly Media
Published: 2012-04-08T16:00:00+00:00


Augmenting Classes

JavaScript’s prototype-based inheritance mechanism is dynamic: an object inherits properties from its prototype, even if the properties of the prototype change after the object is created. This means that we can augment JavaScript classes simply by adding new methods to their prototype objects. Here is code that adds a method to our Range class:

// Return a new range with negated endpoints Range.prototype.negate = function() { return new Range(-this.to, -this.from); };

The prototype object of built-in JavaScript classes is also “open” like this, which means that we can add methods to numbers, strings, arrays, functions, and so on. Here are some examples:

// Invoke the function f this many times, passing the // iteration number. E.g., to print "hello" 3 times: // var n = 3; // n.times(function(n) { console.log(n + " hello"); }); Number.prototype.times = function(f, context) { var n = Number(this); for(var i = 0; i < n; i++) f.call(context, i); }; // Define the ES5 String.trim() method if it does not // exist. This method trims space from the start and end. String.prototype.trim = String.prototype.trim || function() { if (!this) return this; return this.replace(/^\s+|\s+$/g, ""); }; // Return a function's name or "". If it has a name // property, use it. Otherwise, convert the function to // a string and extract the name from that. Function.prototype.getName = function() { return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]; };

It is possible to add methods to Object.prototype, making them available on all objects. This is not recommended, however, because prior to ECMAScript 5, there is no way to make these add-on methods nonenumerable, and if you add properties to Object.prototype, those properties will be reported by all for/in loops.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.